package middleware

import (
	"errors"
	"github.com/gin-gonic/gin"
	jwt "github.com/golang-jwt/jwt/v4"
	"gvb_server/global"
	"gvb_server/models/system/resp/code"
	useJwt1 "gvb_server/utils/jwt"
	uilstime "gvb_server/utils/time"
	"strings"
	"time"
)

func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		useJwt := useJwt1.NewJWT()
		cookies := c.Request.Header.Get("cookie")
		//判断是否为空
		if cookies == "" {
			code.ErrorWithMsg(c, code.TokenExpiredToken, "未登录或非法访问")
			c.Abort()
			return
		}
		split := strings.Split(cookies, ";")
		for _, v := range split {
			if strings.Contains(v, "token") {
				cookies = strings.Split(v, "=")[1]
				break
			}
		}
		token := cookies
		if token == "" {
			code.ErrorWithMsg(c, code.TokenExpiredToken, "未登录或非法访问")
			c.Abort()
			return
		}
		// parseToken 解析token包含的信息
		claims, err := useJwt.ParseToken(token)
		if err != nil {
			if errors.Is(err, useJwt1.TokenExpired) {
				code.ErrorWithMsg(c, code.TokenExpiredToken, "未登录或非法访问")
				c.Abort()
				return
			}
			code.ErrorWithError(c, code.RequestGenericError, err)
			c.Abort()
			return
		}
		if claims.ExpiresAt.Unix()-time.Now().Unix() < claims.BufferTime {
			dr, _ := uilstime.ParseDuration(global.Config.JWT.ExpiresTime)
			claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(dr))
			newToken, _ := useJwt.CreateTokenByOldToken(token, *claims)
			c.SetCookie("token", newToken, 3600, "", "", false, true)
		}
		c.Set("claims", claims)
		c.Next()
	}
}
